package com.learn.controller;

import com.alibaba.fastjson.JSONObject;
import com.learn.mapper.UserMapper;
import com.learn.pojo.User;
import com.learn.service.UserService;
import com.learn.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @description: 描述
 * @author: Mr.Hu
 * @create: 2022/3/15 17:09
 **/
@Controller
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    UserMapper userMapper;
    @Autowired
    TokenUtil tokenUtil;

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    @RequestMapping("/toRegister")
    public String toRegister() {
        return "register";
    }

    @RequestMapping("/login")
    public String Login(HttpServletRequest request, @RequestParam("userName") String userName, @RequestParam("password") String password,Model model) {

        User user = userService.queryByNandP(userName, password);
        if (user == null) {
            String msg = "用户名不存在或密码错误";
            model.addAttribute("msg",msg);
            return "login";
        } else {
            String token = tokenUtil.getToken(user);
            HttpSession session = request.getSession();
            session.setAttribute("userId",user.getUserID());
            session.setAttribute("token", token);
            return "main";
        }
    }

    //    @RequestMapping("/","/register")
//    public String index(){
//        System.out.println("debug:"+"index");
//        return "register";
//    }
    @RequestMapping("/register")

    public String addUser(HttpServletRequest request, @RequestParam("userName") String userName, @RequestParam("password") String password, Model model) {
        try {
            int result = userService.insertUser(userName, password);
        }catch (Exception e){

            String msg = "注册失败";
            model.addAttribute("msg",msg);
            return "register";
        }
            return "login";

    }
    @RequestMapping("/checkUserExit")
    @ResponseBody
    public String checkUserExit( @RequestBody String userName){
        JSONObject jsonObject = JSONObject.parseObject(userName);
        System.out.println(jsonObject);
        String userName1 = jsonObject.getString("userName");
        return  userService.checkUser(userName1);
    }
}


